﻿using ADManage.api.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using XF.Meeting.Api.Models;
using XF.Meeting.Entity.CommonEntity;

namespace XF.Meeting.Api.Filters
{
    public class MeetingAttribute:AuthorizeAttribute
    {
        public static readonly string secretKey =   UCommonWork.Common.Commons.MD5DecodeString(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["secret"]));
        private string errmessage = "";
        /// <summary>
        /// 请求先经过AuthenticateAsync
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {

            // 1、获取token
            actionContext.Request.Headers.TryGetValues("auth", out var tokenHeaders);

            // 2、如果没有token，不做任何处理
            if (tokenHeaders == null || !tokenHeaders.Any())
            {
                return false;
            }


            // 3、如果token验证通过，则写入到identity，如果未通过则设置错误
            var jwtHelper = new JWTHelper();

            var payLoadClaims = jwtHelper.DecodeToObject(tokenHeaders.FirstOrDefault(), secretKey, out string newtoken, out bool isValid, out string errMsg);

            if (isValid)
            {

                //   actionContext.Response.Headers.Add("nihao", "啊打发似的");
                if (newtoken != "")
                {
                    HttpContext.Current.Response.Headers.Set("newT", newtoken);
                    HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "newT");

                }
                var user = new LoginUser();
                var identity = new ClaimsIdentity("jwt", "user", "role");//只要ClaimsIdentity设置了authenticationType，authenticated就为true，后面的authority根据authenticated=true来做权限
                foreach (var item in payLoadClaims)
                {
                    switch (item.Key)
                    {
                        case "userName":
                            user.UserName = item.Value.ToString();
                            identity.AddClaim(new Claim(item.Key, item.Value.ToString()));
                            break;
                        case "IsAdmin":
                            user.IsAdmin = Convert.ToInt32(item.Value);
                            identity.AddClaim(new Claim(item.Key, item.Value.ToString()));
                            break;
                        case "role":
                            user.Roles = item.Value.ToString();
                            identity.AddClaim(new Claim(item.Key, item.Value.ToString()));
                            break;
                        case "RegionalId":
                            identity.AddClaim(new Claim(item.Key, item.Value.ToString()));
                            break;
                        case "RegionName":
                            identity.AddClaim(new Claim(item.Key, item.Value.ToString()));
                            break;
                        case "OrgId":
                            identity.AddClaim(new Claim(item.Key, item.Value.ToString()));
                            break;
                        case "UserId":
                            identity.AddClaim(new Claim(item.Key, item.Value.ToString()));
                            break;
                            //case "email":
                            //    user.Roles = item.Value.ToString();
                            //    break;
                            //case "UserId":
                            //    user.Roles = item.Value.ToString();
                            //    break;

                    }
             
                    // 一个用户只有一种角色


                    //foreach (var roleItem in keyValuePair.Value.ToString().Split(','))
                    //{
               //     identity.AddClaim(new Claim(item.Key, item.Value.ToString()));


                }
                // 最好是http上下文的principal和进程的currentPrincipal都设置
                actionContext.RequestContext.Principal = new ClaimsPrincipal(identity);
                Thread.CurrentPrincipal = new ClaimsPrincipal(identity);

                //if (user.IsAdmin)
                //{
                //    return true;
                //}
                //else
                //{
                //    var controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                //    var actionName = actionContext.ActionDescriptor.ActionName;
                //    if (controllerName == "User")
                //    {
                //        return true;
                //    }
                //}
                return true;
            }
            else
            {
                errmessage = errMsg;
                return false;
            }

        }


        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
         // HttpContext.Current.Response.Redirect("www.baidu.com");
            var erModel = new ErrorBase
            {
                success = false,
                IsAuthorized=false,
                data = "",
                errmsg = errmessage
            };
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, new ObjBase<ErrorBase>()
            {
                obj = erModel,
                secret = "123"
            }, "application/json");
        }
    }
}